// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'ling-prod-7gcd7t0d5ffa0b3b'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  let dbName = event.dbName
  let filter = event.filter ? event.filter : {}

  // 查询数据条数
  const countResult = await db.collection(dbName).count()

  /**
   * 小程序端在获取集合数据时服务器一次默认并且最多返回 20 条记录，云函数端这个数字则是 100
   */

  if (dbName == "t_comments") {
    console.log("查询留言数据，需要排序~");
    return db.collection(dbName).where(filter).orderBy('createTime','desc').get().then(res => {
      res.count = countResult
      return res;
    })
  } else if(dbName == "t_wx-blog"){
    let startIndex = event.startIndex
    console.log("查询blog文章数据，需要排序和分页startIndex：",startIndex);
    //从数据库中索引号startIndex开始查询，每次返回15条数据
    return db.collection(dbName).where(filter).skip(startIndex).limit(15)
            .orderBy('createTime','desc').get().then(res => {
      res.count = countResult
      return res;
    })
  }
  return db.collection(dbName).where(filter).get().then(res => {
    res.count = countResult
    return res;
  })

}